import { navigateTo, switchTab } from "@tarojs/taro";
import { isH5, isWeapp } from "@/utils/env";
import { objToStr } from "@/utils/uri";
import { router } from "./config";

export const goTo = (oParams: IGoTo) => {
  const urlMap = router[oParams.pageType];
  if (!urlMap) return console.error("没找到路径", oParams);

  const suffix = objToStr(oParams.params);

  if (isWeapp) {
    taroGo({ isTabBar: urlMap.isTabBar, url: urlMap.file + suffix });
  } else if (isH5) {
    taroGo({ isTabBar: urlMap.isTabBar, url: urlMap.file + suffix });
  }

  function taroGo({ isTabBar, url }) {
    if (isTabBar) switchTab({ url });
    else navigateTo({ url });
  }
};

interface IGoTo {
  pageType: keyof typeof router;
  params?: IGoToParams;
}

interface IGoToParams {
  [str: string]: string | number;
}
